<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    label-width="150px"
                    :rules="formDataRules"
                    ref="formDataRef"
                >
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="验收编号">
                                {{ formData.billNo }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="机构">
                                {{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="业务类型"
                                prop="businessTypeKey"
                            >
                                <el-select
                                    v-model="formData.businessTypeKey"
                                    placeholder="请选择"
                                    v-if="!isRedSingle"
                                    @change="businessTypeKeyChange"
                                >
                                    <el-option
                                        v-for="item in businessTypeList"
                                        :key="item.key"
                                        :label="item.value"
                                        :value="item.key"
                                    >
                                    </el-option>
                                </el-select>
                                <span v-else>{{
                                    formData.businessTypeValue
                                }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="源单编号"
                                :prop="formData.businessTypeKey !== '6' ? 'sourceNo' : 'sourceNos'"
                                v-if="isRedSingle"
                            >
                                <span>
                                    {{ formData.sourceNo }}
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="sourceNoClick"
                                        v-if="formData.sourceNo && formData.businessTypeKey !== '6'"
                                    ></i>
                                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="formData.redBillState == 3">
                        <el-col :span="12">
                            <el-form-item label="供方" prop="supplierName">
                                <!-- <el-input
                                    v-model="formData.supplierName"
                                    readonly
                                    v-if="formData.redBillState != '3'"
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="supplierNameClick"
                                    ></i>
                                </el-input> -->
                                <span>{{ formData.supplierName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="采购人员" prop="purchaserName">
                                {{ formData.purchaserName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if="isRedSingle">
                            <!-- 汇总验收明细金额+进场费 -->
                            <el-form-item
                                label="验收金额(元)"
                                prop="acceptanceAmount"
                            >
                                {{ formData.acceptanceAmount }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="验收人员">
                                <el-input
                                    v-model="formData.acceptancerName"
                                    readonly
                                    v-if="!isRedSingle"
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="acceptancerNameClick"
                                    ></i>
                                </el-input>
                                <span v-else>{{
                                    formData.acceptancerName
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if="isRedSingle">
                            <!-- 汇总服务费用明细金额,可为0 -->
                            <el-form-item
                                label="服务费用(元)"
                                prop="transportationCost"
                            >
                                {{ formData.transportationCost }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="验收日期"
                                prop="acceptanceDate"
                            >
                                <el-date-picker
                                    v-model="formData.acceptanceDate"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd"
                                    :clearable="false"
                                    v-if="!isRedSingle"
                                >
                                </el-date-picker>
                                <span v-else>{{
                                    formData.acceptanceDate
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="验结一体"
                                :prop="
                                    formData.isAccepSettle
                                        ? 'invoiceNo'
                                        : 'invoiceNos'
                                "
                            >
                                <el-checkbox
                                    v-model="formData.isAccepSettle"
                                    label=""
                                    style="margin-right: 10px"
                                    :disabled="isRedSingle"
                                ></el-checkbox>
                                <el-input
                                    placeholder="请填写发票号"
                                    v-model="formData.invoiceNo"
                                    v-enterInteger1
                                    v-show="formData.isAccepSettle"
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{ formData.invoiceNo }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="formData.redBillState == 3">
                            <el-form-item label="税率%" prop="taxRate">
                                <!-- <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxRate"
                                    @input.native="onInput0_100"
                                    v-enterFloat
                                    v-if="!isRedSingle"
                                ></el-input> -->
                                <span>{{ formData.taxRate }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="formData.redBillState == 3">
                        <el-col :span="12">
                            <el-form-item label="税额" prop="taxAmount">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxAmount"
                                    v-enter-float="{
                                        set: formData,
                                        key: 'taxAmount'
                                    }"
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{ formData.taxAmount }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="税价合计"
                                prop="totalPriceAndTax"
                            >
                                {{ formData.totalPriceAndTax }}元
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="formData.redBillState == 3">
                        <el-col :span="12">
                            <el-form-item label="币种" prop="currencyId">
                                <!-- <el-select
                                    v-model="formData.currencyId"
                                    placeholder="请选择"
                                    v-if="
                                        (formData.businessTypeKey == 0 || formData.businessTypeKey == 2) && !isRedSingle
                                    "
                                    @change="currencyChange"
                                >
                                    <el-option
                                        v-for="item in currencyForm"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select> -->
                                <span>{{ formData.currency }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="本位币" prop="baseCurName">
                                {{ formData.baseCurName }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row v-if="formData.redBillState == 3">
                        <el-col :span="12">
                            <el-form-item
                                label="本位币汇率"
                                prop="baseCurExchangeRate"
                            >
                                {{ formData.baseCurExchangeRate }}
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="12">
                            <el-form-item label="验收金额(本位币)">
                                {{ formData.baseAcceptanceAmount }}
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <!-- 只有内租 外租才显示该字段 -->
                            <!-- <el-form-item
                                label="进场费(元)"
                                prop="approachCost"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.approachCost"
                                    v-enterFloat2
                                    @blur="approachCostBlur"
                                ></el-input>
                            </el-form-item> -->
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="传财务共享">
                                {{ formData.easId ? '已传' : '未传'}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结算编号" v-show='formData.settleNo'>
                                <span style="color: blue;cursor: pointer;" @click='settlementNoClick'>{{formData.settleNo}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="备注">
                            <el-input
                                type="textarea"
                                :rows="2"
                                resize="none"
                                placeholder="请输入内容"
                                v-model="formData.remarks"
                                maxlength='500'
                            >
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                {{ showState(formData.state) }}
                                <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="冲红单"
                                ><span :style="redBillStateStyle">{{
                                    redBillStateFun
                                }}</span></el-form-item
                            >
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button type="primary" style="background: #2e61d7" @click="save"
                >保存</el-button
            >

            <el-button @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState } from 'vuex'
import {
    formatDate,
    showLoading,
    hideLoading,
    openAppClient
} from '@/utils/common'
import request from '@/api/settlementManagement/acceptanceManagement/weeklyMaterialAcc'

export default {
    data () {
        return {
            //表单数据
            formData: {
                billNo: '', //验收编号
                orgName: '', //所属机构
                businessTypeKey: '', //业务类型
                sourceNo: '', //源单编号
                supplierName: '', //供应商
                purchaserName: '', //采购人员
                purchasingUnitName: '', //采购单位
                acceptancerName: '', //验收人员
                acceptanceAmount: '', //验收金额
                acceptanceDate: formatDate(new Date(), 'yyyy-MM-dd'), //验收日期
                isAccepSettle: false, //验结一体
                transportationCost: 0, //运输单位费用
                taxRate: '', //税率
                totalAmount: '', //税价合计
                taxAmount: '', //税额
                currency: '', //币种
                isSharing: '', //传财务共享
                baseAcceptanceAmount: '', //验收金额(本位币)
                baseCurName: '', //本位币
                settleNo: '', //结算编号
                redBillState: -1,
                remarks: '', //备注
                state: 0, //状态
                acceptanceQuantity: 0,
                acceptancerId: '',
                baseCurId: '',
                baseCurExchangeRate: '',
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                currencyId: '',
                easId: '',
                founderId: null,
                founderName: null,
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                purchaserId: '',
                purchasingUnitId: '',
                rmbAcceptanceAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settleId: '',
                sourceId: '',
                sourceNumber: '',
                supplierId: '',
                workId: '',
                redBillId: '',
                redBillNo: '',
                approachCost: 0,
                billSource: 0,
                businessTypeValue: '',
                hasInvoice: 0,
                parentId: '',
                totalPriceAndTax: 0
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            businessTypeList: [
                {
                    key: '0',
                    value: '物资采购合同'
                },
                {
                    key: '1',
                    value: '临时需用计划(自购)'
                },
                {
                    key: '2',
                    value: '周材调拨'
                },
                {
                    key: '6',
                    value: '事实合同'
                }
            ],
            formDataRules: {
                businessTypeKey: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'blur'
                    }
                ],
                supplierName: [
                    {
                        required: true,
                        message: '请选择供应商',
                        trigger: 'blur'
                    }
                ],
                sourceNo: [
                    {
                        required: true,
                        message: '请选择源单编号',
                        trigger: 'blur'
                    }
                ],
                purchaserName: [
                    {
                        required: true,
                        message: '请选择采购人员',
                        trigger: 'blur'
                    }
                ],
                acceptanceAmount: [
                    {
                        required: true,
                        message: '请输入验收金额',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                totalPriceAndTax: [
                    {
                        required: true,
                        message: '请输入税价合计',
                        trigger: 'blur'
                    }
                ],
                transportationCost: [
                    {
                        required: true,
                        message: '请输入服务费用',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],
                invoiceNo: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ],
                baseCurExchangeRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ]
            },
            isRedSingle: false,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            isbaseCurExchangeRate: true
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },

        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        'formData.isAccepSettle' () {
            // 如果验结一体未勾选,则需要清除发票号的提示信息
            if (!this.formData.isAccepSettle) {
                this.$refs.formDataRef.clearValidate('invoiceNo')
                this.formData.invoiceNo = ''
            }
        },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' () {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isbaseCurExchangeRate = true
                this.formData.baseCurExchangeRate = 1
            } else {
                this.isbaseCurExchangeRate = false
                this.formData.baseCurExchangeRate = null
            }
        },
        // // 监听验收金额
        // 'formData.acceptanceAmount' () {
        //     // 税价合计 = 验收金额 + 税额
        //     this.formData.totalPriceAndTax =
        //         +this.formData.acceptanceAmount + +this.formData.taxAmount
        //     // 验收金额(本位币) = 验收金额 * 本位币汇率
        //     this.formData.baseAcceptanceAmount =
        //         +this.formData.acceptanceAmount *
        //         +this.formData.baseCurExchangeRate
        // },
        // // 监听税额
        // 'formData.taxAmount' () {
        //     // 税价合计 = 验收金额+税额
        //     this.formData.totalPriceAndTax =
        //         +this.formData.acceptanceAmount + +this.formData.taxAmount
        // },

        // 监听进场费
        // 'formData.approachCost' () {
        // 验收金额 = 验收明细金额+进场费;  还需汇总验收明细金额,后续补上
        // 进场费会影响验收金额, 验收金额影响验收金额（本位币）和 税价合计
        //     this.formData.acceptanceAmount = +this.formData.approachCost +
        // },

        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    components: {},
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.formData.orgId = this.orgId
        this.formData.orgName = this.orgName
        // this.formData.purchaserName = localStorage.getItem('userName')
        this.formData.acceptancerName = localStorage.getItem('userName')
        const { baseCyByOrgId } = this.userInfo
        this.formData.baseCurName = baseCyByOrgId.currencyName //本位币
        this.formData.baseCurId = baseCyByOrgId.currency
        this.$route.query.isRedSingle === '1'
            ? (this.isRedSingle = true)
            : (this.isRedSingle = false)
        if (this.isRedSingle) {
            this.getRedList()
        }
    },
    mounted () {},
    beforeDestroy () {},
    methods: {
        // 如果是点击冲红单进入的新增页,则需要返显数据,只有备注能修改,其余均不能修改
        async getRedList () {
            showLoading()
            try {
                let data = await request.redSingle(this.$route.query.billid)
                this.redFormData = this._.cloneDeep(data)
                data.currency = this.currencyForm.find(
                    x => x.value === data.currencyId
                ).label

                this.formData = data
            } finally {
                hideLoading()
            }
        },
        // 源单编号-跳转到 ...的详情页
        sourceNoClick () {
            let url = ''
            let name = ''
            switch (this.formData.businessTypeKey) {
            case '0':
                url = '/momentNeedPlanShow'
                name = '临时需用计划查看页'
                break
            case '1':
                url = '/ctMaterialApplyShow'
                name = '物资采购合同查看页'
                break
            case '2':
                url = '/revolveAllocationShow'
                name = '调拨单查看页'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.sourceId}&isview=${true}`,
                `${name}`
            )
        },
        // 结算编号-跳转到周材采购结算详情页
        settlementNoClick () {
            openAppClient(
                `/purchaseSettlementAcceptanceAndSettlement?isview=${true}&billid=${
                    this.formData.settleId
                }`,
                '查看周材采购结算'
            )
        },
        // 选择验收人员
        async acceptancerNameClick () {
            let data = await request.getAcceptancerName()
            this.formData.acceptancerId = data.userId
            this.formData.acceptancerName = data.userName
        },

        // 供方后面: 选择入库明细
        async supplierNameClick () {
            if (this.formData.businessTypeKey === '') {
                return this.clientPop('err', '请先选择业务类型')
            }
            let res = await request.getWarehousingList({
                businessTypeKey: this.formData.businessTypeKey, //必传
                parentId: '0'
            })
            let data = res[0]
            // val是关闭弹窗后,返回的数据
            this.formData.supplierName = data.supplierName // 供应商
            this.formData.supplierId = data.supplierId // 供应商ID
            this.formData.purchaserName = data.purchasingPersonnelName // 采购人员名称
            this.formData.purchaserId = data.purchasingPersonnelId // 采购人员ID
            this.formData.sourceNo = data.billNo // 源单编号
            this.formData.sourceId = data.billId // 源单ID
            this.formData.baseCurName = data.baseCurName // 本位币名称
            this.formData.baseCurId = data.baseCurId // 本位币ID
            this.formData.taxRate = data.taxRate // 物资采购合同：带入合同税率。

            // 如果选择合同和周材调拨源单带入数据，计划和事实合同类型，由用户下拉单选
            if (
                this.formData.businessTypeKey == 0 ||
                this.formData.businessTypeKey == 2
            ) {
                this.formData.currency = data.currency // 币种名称
                this.formData.currencyId = data.currencyId // 币种ID
            } else {
                let result = await request.getCurrency(data.billId)
                this.formData.currency = result.currency // 币种名称
                this.formData.currencyId = result.currencyId // 币种ID
            }
        },
        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        // 本位币汇率不能为0
        baseCurExchangeRateBlur () {
            if (this.formData.baseCurExchangeRate == 0) {
                this.formData.baseCurExchangeRate = null
            }
            this.formData.baseAcceptanceAmount =
                +this.formData.acceptanceAmount *
                +this.formData.baseCurExchangeRate
        },
        // 当币种切换时,获取人民币汇率
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
        },
        // 业务类型切换时,获取中文名
        businessTypeKeyChange (val) {
            this.formData.businessTypeValue = this.businessTypeList.find(
                item => item.key == val
            ).value
        },

        //保存按钮
        save () {
            this.$refs.formDataRef.validate(valid => {
                if (!valid) return false
                if (this.isRedSingle) {
                    this.redFormData.remarks = this.formData.remarks
                }
                request
                    .WeeklyMaterialAdd(
                        this.isRedSingle ? this.redFormData : this.formData
                    )
                    .then(res => {
                        this.clientPop(
                            'info',
                            '保存成功,是否继续',
                            () => {
                                this.$router.replace({
                                    path: '/weeklyMaterialAccEdit',
                                    query: {
                                        billid: res,
                                        name: 'receivingMaterials'
                                    }
                                })
                            },
                            null,
                            this.handleClose
                        )
                    })
            })
        },
        //取消按钮
        handleClose () {
            this.$router.replace('/weeklyMaterialAccList')
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
</style>
